package com.easy.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.Random;


@Component
public class EmailUtil {
    private static final String FROM = "2480379037@qq.com"; // 发件人邮箱
    private static final String AUTH_CODE = "zowtnaudwjmwebaf"; // 邮箱授权码（不是QQ密码）
    private static final String HOST = "smtp.qq.com"; // QQ 邮箱的SMTP服务器
    private static final String PORT = "465"; // SSL端口

    //用 QQ 邮箱 SMTP 配置建立一个邮件会话
    private static final Session session;
    static {
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });
        //开启debug模式
        //session.setDebug(true);
    }
    //提供 sendEmail 方法发送邮件（支持 HTML 格式内容）
    public static void sendEmail(String to, String text) {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("农村爱心水果管理系统验证码");
            //message.setText(text);
            message.setContent("<h1 style='color:red'>验证码:"+text+"</h1>","text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
           e.printStackTrace();
        }

    }
    // 生成验证码并发送邮件
    public static String generateAndSendCode(String to) {
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(1000000));
        sendEmail(to, code);  // 发送验证码
        return code;
    }
}
